package me.chyxion.spring.ext.codegen.services;

import java.io.File;
import me.chyxion.spring.ext.codegen.CodeGenCustomizer;
import me.chyxion.spring.ext.codegen.CodeGenCustomizer.CodeGenArgs;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.CharEncoding;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br />
 * chyxion@163.com <br />
 * Oct 6, 2014 1:10:55 PM
 */
public abstract class CodeGenerator {
	@Autowired(required = false)
	private List<CodeGenCustomizer> customizers;
	@Autowired
	protected CodeGenBaseTool baseTool;
	protected String codeDir = "src/main/java/";
	protected String testDir = "src/test/java/";
	protected String resourcesDir = "src/main/resources/";
	protected String viewsDir = "src/main/webapp/assets/js/views/";

	/**
	 * @param dataModel
	 * @param module
	 * @param model
	 */
	public abstract String process(Map<String, Object> dataModel, String module, String model);

	/**
	 * render FreeMarker Tpl
	 * @param file
	 * @param ftl
	 * @param model
	 * @return
	 */
	protected String render(CharSequence file, String ftl, Map<String, Object> model) {
    	try {
    		// customize
    		CodeGenArgs args = new CodeGenArgs(String.valueOf(file), ftl, model);
    		if (customizers != null && customizers.size() > 0) {
    			for (CodeGenCustomizer customizer : customizers) {
    				customizer.customize(args);
				}
    		}
    		// write result
	        FileUtils.write(new File(baseTool.getProjDir(), args.getFile()), 
	        	baseTool.renderFtl(args.getFtl(), args.getModel()), 
	        	CharEncoding.UTF_8);
    		return args.getFile();
        }
    	catch (Exception e) {
    		throw new RuntimeException("Code Generate Write File ERROR, [" + e.getMessage() + "].", e);
        }
	}
}
